<template>
	<div :id="pageNumber" :class="['pageNo',{'pageNo-hide':!list.length}]">
		<template v-for="(item,index) in list" :key="index">
			<div>
				<template v-for="(item_2,index_2) in item" :key="index_2">
					<template v-if="item_2?.type == 'text'">
						<span :class="[clasName(item_2)]" :style="[textStyle(item_2)]" v-html="item_2.Value"></span>
					</template>
					<template v-if="item_2?.type == 'image'">
						<span class="image">
							<lazy-load-image class="img" :image="item_2.Path" imgMode="heightFix" :height="imageHeight(item_2)" @click.async="previewImage(item_2.Path)" />
						</span>
					</template>
					<template v-if="item_2?.type == 'groupImage'">
						<div class="group-image">
							<div v-for="(item_3,index_3) in item_2.images" :key="index_3" :style="[groupImageStyle(item_3)]">
								<lazy-load-image class="img" :image="item_3.Path" imgMode="widthFix" :height="imageHeight(item_3)" @click.async="previewImage(item_3.Path)" />
							</div>
						</div>
					</template>
					<template v-if="item_2?.type == 'table'">
						<preview-table :border="item_2.line==1" emptyText="暂无更多数据" :width="item_2.width">
							<preview-tr v-for="(item_3,index_3) in item_2.tables" :key="index_3">
								<preview-td v-for="(item_4,index_4) in item_3" :key="index_4" :width="item_4.Width">
									<template v-for="(item_5,index_5) in item_4.datas" :key="index_5">
										<span :class="[clasName(item_5)]" :style="[textStyle(item_5,'table')]" v-html="item_5.Value" v-if="item_5.type=='text'"></span>
										<span class="image" v-if="item_5.type=='image'" :style="{width:item_5.Width*0.6+'px'}">
											<lazy-load-image class="img" :image="item_5.Path" imgMode="widthFix" :height="imageHeight(item_5)" />
										</span>
									</template>
								</preview-td>
							</preview-tr>
						</preview-table>
					</template>
				</template>
			</div>
		</template>
	</div>
</template>
<script>
	export default {
		props: {
			item: {
				type: Object,
				default () {
					return {
						datas: []
					}
				}
			},
			zone: {
				type: Number,
				default: 50
			}
		},
		data() {
			return {
				getThreshold: -100,
				padding: 24,
				sum: 0,
				defaultSize: 16,
				minSize: 16,
				maxSize: 18,
				minSizeTable: 14,
				resultArray: []
			}
		},
		mounted() {
			// 由父组件生命周期onReachBottom发出，目的是让页面到底时，保证所有都进行加载，做到绝对稳定且可靠
			this.$nextTick(() => {
				uni.$once('onReachBottom', () => {
					this.$emit('itemShow', { s: this.item.s, e: this.item.e });
				});
			})
			setTimeout(() => {
				this.createObserver();
			}, 20)
		},
		computed: {
			pageNumber() {
				return `page_${this.item.e/this.zone}`;
			},
			list() {
				const newArray = [];
				const items = this.item.datas;
				for (let k in items) {
					for (let k2 in items[k]) {
						switch (k2.split('_')[0]) {
							case 'Text':
								this.get_text(+k, items[k]);
								break;
							case 'Image':
								this.get_image(+k, items[k]);
								break;
							case 'GroupImage':
								this.get_group_image(+k, items[k]);
								break;
							case 'Table':
								this.get_table(+k, items[k]);
								break;
						}
					}
				}
				// console.log('this.resultArray', this.resultArray)
				return this.resultArray;
			}
		},
		methods: {
			// 处理文本
			get_text(index, data) {
				for (let k in data) {
					if (k.indexOf('Text_') > -1 && !data[k].index) {
						const idx = k.split('Text_')[1];
						this.get_text_br(data[k]);
						this.get_text_underline(data[k]);
						this.filter_char(data[k]);
						data[k].type = 'text';
						data[k].index = idx;
						data[k].Value = data[k].Value.replace(/ /g, '&nbsp;');
						const datas = !this.resultArray[index] ? [] : this.resultArray[index];
						datas[idx] = data[k];
						this.resultArray[index] = datas;
					}
				}
			},
			// 处理图片
			get_image(index, data) {
				for (let k in data) {
					if (k.indexOf('Image_') > -1 && data[k].Path.trim() != '' && !data[k].index) {
						const idx = k.split('Image_')[1];
						data[k].type = 'image';
						data[k].index = idx;
						data[k].Path = this.get_image_url(data[k]);
						const datas = !this.resultArray[index] ? [] : this.resultArray[index];
						datas[idx] = data[k];
						this.resultArray[index] = datas;
					}
				}
			},
			// 处理批量图片
			get_group_image(index, data) {
				for (let k in data) {
					if (k.indexOf('GroupImage_') > -1) {
						const idx = k.split('GroupImage_')[1];
						const arr = [];
						const obj = data[k];
						for (let k2 in obj) {
							if (k2.indexOf('Image_') > -1 && obj[k2].Path.trim() != '' && !obj[k2].index) {
								obj[k2].type = 'image';
								obj[k2].index = k2.split('Image_')[1];
								obj[k2].Path = this.get_image_url(obj[k2]);
								arr.push(obj[k2]);
							}
						}
						const items = arr;
						const datas = !this.resultArray[index] ? [] : this.resultArray[index];
						datas[idx] = { type: 'groupImage', images: items };
						this.resultArray[index] = datas;
					}
				}
			},
			// 处理表格
			get_table(index, data) {
				for (let k in data) {
					if (k.indexOf('Table_') > -1) {
						const datas = !this.resultArray[index] ? [] : this.resultArray[index];
						const t = [];
						const o = data[k];
						let lineStyle = 1;
						for (let i in o) {
							this.get_table_con(o[i]);
							lineStyle = o[i]?.LineStyle == 0 ? 0 : 1;
							const rIdx = o[i]['Row'];
							const rData = t[rIdx] ? t[rIdx] : [];
							rData.push(o[i]);
							t[rIdx] = rData;
						}
						const datas_new = datas.concat([{ type: 'table', width: this.sum, line: lineStyle, tables: t }]);
						this.resultArray[index] = datas_new;
						// console.log(index, datas_new)
					}
				}
			},
			// 处理table中的文本
			get_table_con(data) {
				if (data.end) return;
				for (let k in data) {
					switch (k.split('_')[0]) {
						case 'Text':
							this.get_text_underline(data[k]);
							this.get_text_br(data[k]);
							this.filter_char(data[k]);
							const idx = k.split('Text_')[1];
							data[k].type = 'text';
							let arr = data.datas ? data.datas : [];
							arr[idx] = data[k];
							data['datas'] = arr;
							data.end = true;
							break;
						case 'Width':
							if (data.IsFirstCell) this.sum = data.Width;
							else this.sum += data.Width;
							break;
						case 'Image':
							if (data[k].Path.trim() != '') {
								const idx = k.split('Image_')[1];
								data[k].type = 'image';
								data[k].Path = this.get_image_url(data[k]);
								let arr = data.datas ? data.datas : [];
								arr[idx] = data[k];
								data['datas'] = arr;
							}
							data.end = true;
							break;
					}
				}
			},
			/**
			 * 处理图片地址
			 * @param {Object} item 图片对象
			 */
			get_image_url(item) {
				return item.Path.replace(/dev-view-json.book118.com/g, '192.168.0.105:9012').replace('https', 'http');
			},
			/**
			 * 处理文本下划线
			 * @param {Object} item
			 */
			get_text_underline(item) {
				if (item.Value.indexOf('_') > -1 && item.Underline == 1) {
					item.Value = item.Value.replace(/_/g, '&nbsp;');
				}
			},
			/**
			 * 处理文本符号\u000b
			 * @param {Object} data
			 */
			get_text_br(item) {
				if (item.Value.indexOf('\u000b') > -1) {
					item.Value = item.Value.replace(/\u000b/g, '<br>');
				}
			},
			filter_char(item) {
				if (['\f', '\a', '\b', '\n', '\r', '\t', '\v'].indexOf(item.Value) > -1) {
					item.Value = item.Value.replace(/(\a|\f|\b|\n|\r|\t|v)/g, '');
				}
			},
			/**
			 * 文本的样式
			 * @param {Object} item 文本信息
			 */
			textStyle(item, type = 'text') {
				const style = {};
				let size = item.Size;
				size = !size ? this.defaultSize : size;
				size = size > this.maxSize ? this.maxSize : size;
				size = size < this.minSize ? type == 'table' ? this.minSizeTable : this.minSize : size;
				style['font-size'] = `${size}px`;
				if (['Times New Roman'].indexOf(item.Font)) style['font-family'] = 'Times New Roman';
				return style;
			},
			/**
			 * 集合图片的样式
			 * @param {Object} groupImage 图片集合
			 */
			groupImageStyle(item) {
				const style = {};
				style.width = `${item.Width}px`
				return style;
			},
			createObserver() {
				this.disconnectObserver('contentObserver');
				let contentObserver;
				// #ifdef H5
				contentObserver = uni.createIntersectionObserver();
				// #endif
				// #ifndef H5
				contentObserver = uni.createIntersectionObserver(this);
				// #endif
				contentObserver.relativeToViewport({
					bottom: this.getThreshold,
				}).observe(`#${this.pageNumber}`, (res) => {
					if (res.intersectionRatio > 0) {
						this.$emit('itemShow', { s: this.item.s, e: this.item.e });
						// 如果图片已经加载，去掉监听，减少性能的消耗
						this.disconnectObserver('contentObserver');
					}
				})
				this.contentObserver = contentObserver;
			},
			disconnectObserver(observerName) {
				const observer = this[observerName];
				observer && observer.disconnect();
			},
			clasName(item) {
				let className = '';
				if (item.Subscript) {
					className = 's_11';
				}
				if (item.Superscript) {
					className = 's_12';
				}
				if (item.Underline) {
					className += ' s_underline';
				}
				if (item.Bold) {
					className += ' s_bold';
				}
				if (item.Italic) {
					className += ' s_italic';
				}
				if (item.StrikeThrough) {
					className += ' s_line_through';
				}
				return className;
			},
			/**
			 * 设置图片高度
			 * @param {Object} item 图片宽高等参数
			 */
			imageHeight(item) {
				const width = item.Width;
				const height = item.Height;
				let rate = uni.upx2px(750 - this.padding * 2) / width;
				rate = rate > 1 ? 1 : rate;
				return `${height*rate}px`;
			},
			previewImage(url) {
				uni.previewImage({
					urls: [url]
				})
			}
		}
	}
</script>
<style scoped lang="scss">
	$fontSize: 16px;
	.pageNo {
		-webkit-user-select: auto;
		font-family: '微软雅黑', PingFangSC-Regular, sans-serif;
		min-height: 100rpx;
		padding: 0 24rpx;
		overflow: hidden;
		color: #111;
		&>div,
		&>view {
			line-height: 2;
			margin-bottom: 12px;
			font-size: $fontSize;
		}
		&-hide {
			display: none;
		}
	}
	img, span {
		vertical-align: middle;
	}
	.s_2 {
		font-weight: 700;
	}
	.s_11 {
		display: inline-block;
		line-height: 1 !important;
		vertical-align: sub !important;
		font-size: $fontSize;
		transform-origin: 50% 100%;
		transform: scale(0.7);
	}
	.s_12 {
		display: inline-block;
		line-height: 1 !important;
		vertical-align: super !important;
		font-size: $fontSize;
		transform-origin: 50% 100%;
		transform: scale(0.7);
	}
	.s_underline {
		text-decoration: underline;
	}
	.s_bold {
		font-weight: 700;
	}
	.s_italic {
		font-style: italic;
	}
	.s_line_through {
		text-decoration: line-through;
	}
	span {
		word-break: break-word;
	}
	.image {
		display: inline-block;
	}
	.group-image {
		display: flex;
		justify-content: space-between;
		align-items: center;
	}
</style>
